/**
 * 系统配置
 */
var sysconfig = {
	debug:false,
};
/**
 * 公共常量
 */
var CONSTANTS = {
		/**
		 * 路径
		 */
		PATH:{
			BASE_URL:"",
		},
		/**
		 * 颜色
		 */
		COLOR:{
			RED:"#FF0000",
		}
}
/**
 * 公共方法对象
 */
var sys = {

   /**
    * 模块显示
    */
	initShowSetInfo:function(){
		const REMOVE = 1,HIDE=2,DISABLED=3,IS_HIDE=1;
		const data = window.window._showDataInfo || getShowData();
		//console.log("%c%s%o","color:blue","显示设置信息》》》》",data);
		$(".div-main [s-set]").each(function(i,n){
			var name = $(this).attr("s-name");
			var type = $(this).attr("s-type");
			var hide = $(this).attr("s-hide");
			var _value = data[name];
			if(_value && _value==IS_HIDE && type == REMOVE){//去除
				addActive($(this));
				$(this).remove();
			}else if(_value && _value==IS_HIDE && type == HIDE){//隐藏
				addActive($(this));
				$(this).hide()
			}else if(_value && _value==IS_HIDE && type == DISABLED){//禁用
				addActive($(this));
				$(this).attr("disabled",true);
				$(this).prop("onclick",null).off().unbind();
			}else{
				if(hide) return ;
				$(this).show()
			}
		})
		function addActive(that){
			if(that.hasClass("active")){
				that.removeClass("active");
				that.siblings().removeClass("active");
				that.next().addClass("active");
				that.next().click();
			}
		}
		function getShowData(){
			sys.getNoSyncData("showset/getShowSetInfo",{},function(data){
				window._showDataInfo = data;
			})
			return window._showDataInfo;
		}
	},

	/**
	 * 初始化权限菜单
	 */
	initMenuPower:function(){
		var dealType_Hide = 1;//去掉
		var dealTypeDisabled = 2;//禁用
		$(".div-main [power]").each(function(i,n){
			var isadmin =  $(".admin").attr("data-account") == "admin" ? true :false ;
			var power = $(this).attr("power");
			var allAuth =power.split(".")[0]+".authall";
			if((","+g_usermenu+",").indexOf(","+power.toLowerCase()+",")<0 && (","+g_usermenu+",").indexOf(","+allAuth.toLowerCase()+",")<0 && !isadmin){
				var powertype = $(this).attr("powertype");
				if(!powertype || powertype== dealType_Hide){
					$(this).remove();
				}else{
					$(this).attr("disabled",true);
					$(this).prop("onclick",null).off().unbind();
				}
			}
		})
		sys.initShowSetInfo();
	},

	/**
	 * 预览文件
	 */
	previewFile:function(filepath){
		var Index = showLoading("正在加载预览...");
		var suffix = filepath.substring(filepath.lastIndexOf(".")+1);
		var fileTyle = fileUtils.getFormatClass(suffix);
		if(fileTyle == "img" || fileTyle == "pdf" || fileTyle == "video" || fileTyle == "audio"){
			closeLoading(Index);
			window.open(filepath,"_blank");
		}else if(fileTyle == "doc" || fileTyle == "xls" || fileTyle == "ppt"){//office文件转html预览
			sys.getNoSyncData("i_index/previewFile",{filepath:filepath},function(data){
				closeLoading(Index);
				if(data.code == 0){
					var url = data.data;
					window.open(url);
				}else{
					sys.msg(data);
				}
			})
		}else if(filepath.endsWith(".txt")){
			closeLoading(Index);
			window.location.href = filepath;
		}
	},


	/**
	 * 前往详情页
	 */
	toDetailPage:function(url,title,clickFunc){
		sys.stopPropagation();
		initHtmlNode();
		closeRightSlider();
		$.cookie("cacheIndex", $(".nav-tabs").find("li.active").index());
		$(".detailBody").remove();
		$(".div-main").append(createDetailHtml());
		$(".nav-tabs").find("li").removeClass("active").find(".fh-dels").remove();
		var $newTab = $("<li class='active detailTab' data-url='"+url+"'><a href='javascript:void(0);'>"+title+"</a></li>");
		addCloseBtn($newTab);
		$(".nav-tabs").append($newTab);
		$(".mainBody").hide();
		$.post(url,{},function(data){
			$(".detailBody").html(data);
			removeLastHeader();
		});
		$newTab.on("click", function(){
			//判断是不是列表页（列表页没有data-url属性），是就显示列表页
			var $this = $(this);
			if(!$this.is('[data-url]')){
				$(".mainBody").show();
				$(".detailBody").remove();
				$(".detailTab").remove();
				$(".nav-tabs").find("li").removeClass("active");
				$this.addClass("active");
			}else {
				//判断是否是最后一个tab（有没有.fh-dels子元素），是就不做处理
				if($this.find(".fh-dels").length){
					return;
				}
				//删除后面所有的tab，加上关闭图标，加载这个页面的内容
				$this.nextAll().remove();
				addCloseBtn($this);
				$(".detailBody").empty();
				$this.addClass("active");
				$.post(url,{},function(data){
					$(".detailBody").html(data);
					removeLastHeader();
				});
			}
		});
		$(".nav-tabs li:not(.detailTab)").bind("click",function(){
			$(".mainBody").show();
			$(".detailBody").remove();
			$(".detailTab").remove();
			$(".nav-tabs").find("li").removeClass("active");
			$(this).addClass("active");
		})

		function addCloseBtn($tab){
			var closeBtn = $("<span class='iconfont icon-del-close1 fh-dels'></span>");
			$tab.find("a").append(closeBtn);
			closeBtn.on("click", function(){
				var $this = $(this).parents(".detailTab");
				var $prev = $this.prev();
				if($prev.length && $prev.is('[data-url]')){
					$prev.click();
				}else {
					//回到列表页了
					$(".mainBody").show();
					$(".detailBody").remove();
					$(".detailTab").remove();
					if(__Var && __Var.showIndexFunc){
						__Var.showIndexFunc();
					}else {
						var cacheIndex = $.cookie("cacheIndex");
						console.log("选中的下标:"+cacheIndex);
						$(".nav-tabs").find("li").eq(cacheIndex).addClass("active");
					}
				}
			});
		}
		function removeLastHeader(){
			if($(".page-header").length > 1){
				$(".page-header:last").remove();
			}
		}

		function createDetailHtml(){
			return "<div class='page-content-s detailBody'></div>"
		}
		function initHtmlNode(){
			if($(".page-content-s").length > 0  && !$(".page-content-s:first").hasClass("mainBody")){
				$(".page-content-s:first").addClass("mainBody");
			}
		}
		function closeRightSlider(){
			try {
				if(listRight && listRight instanceof Object){
					listRight.closeLeftData();
				}
			} catch (e) {
				console.log(e);
			}
			try {
				if(closeRightPage && typeof closeRightPage === "function" ){
					closeRightPage();
				}
			} catch (e) {
				console.log(e);
			}
		}
	},

	go2page:function(url){
		location.href=url;
	},

	/**
	 * 弹出的iframe框layer关闭
	 */
	frameDialogClose:function(){
		var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
		parent.layer.close(index); //再执行关闭
	},
	/**
	 * 提示消息
	 * @param d 例如{code:0,msg:"成功",url:"跳转连接",func:成功后执行方法}
	 */
	msg:function(d){
		console.log("msg:",d);
		if(d.code == 0){
			layer.msg(d.msg,{
			    time: 1000,
			    icon:1
			}, function(){
				var url = d.url;
				var func = d.func;
				if(url!=null){
				    parent.loadHtml(url);
				}
				if(func!=null){
					func(d);
				}
			});
		}else if(d.code!=0){
			layer.msg(d.msg,{
			    time: 2000,
			    icon:7
			});
		}
	},
	/**
	 * 提示消息，需手动关闭
	 * @param d 例如{code:0,msg:"成功",url:"跳转连接",func:成功后执行方法}
	 */
	msg2:function(d){
		console.log("msg:",d);
		if(d.code == 0){
			layer.msg(d.msg,{
				time: 0,
				btn: '知道了',
			    icon:1
			}, function(){
				var url = d.url;
				var func = d.func;
				if(url!=null){
				    parent.loadHtml(url);
				}
				if(func!=null){
					func(d);
				}
			});
		}else if(d.code!=0){
			layer.msg(d.msg,{
				time: 0,
			    btn: '知道了',
			    icon:7
			});
		}
	},
	/**
	 * 顶部弹出错误提示
	 * @param msg
	 */
	topmsg:function(msg){
		layer.msg(msg,{offset: '100px',time:1000,anim:6});
	},
	/**
	 * 确认窗口
	 * @param msg 提示内容
	 * @param func 确认后执行的方法
	 * @param param 需要的参数
	 */
	confirm:function(msg,func,param){
		layer.confirm(msg, {icon: 3, title:'提示'}, function(index){
			if(index>=1){
				func(param);
			}
			layer.close(index);
		});
	},

	/**
	 * 弹出窗口
	 * @param icon 图标图片路径
	 * @param title 标题
	 * @param url 弹出文件地址
	 * @param width 宽度
	 * @param heigth 高度
	 */
	window:function(icon,title,url,width,heigth,calbackurl){
		var t = title;
		if(icon!=null && icon!=""){
			t = '<img src="'+icon+'" width="20"/>'+title;
		}
		layer.open({
			  type: 2,
			  title: t,
			  maxmin: false,//是否最大化
			  shadeClose: false, //点击遮罩关闭层
			  area : [width+"" , heigth+""],
			  content: url,
			 /* end:function(){
				  if(calbackurl!=null && calbackurl !=""){
					  loadHtml(calbackurl);
				  }
			  }*/
		});
	},
	/**
	 * 弹出窗口
	 * @param icon 图标图片路径
	 * @param title 标题
	 * @param url 弹出文件地址
	 * @param width 宽度
	 * @param heigth 高度
	 */
	window1:function(icon,title,url,width,heigth,calbackurl){
		var t = title;
		if(icon!=null){
			t = '<img src="'+icon+'" width="20"/>'+title;
		}
		layer.open({
			  type: 2,
			  title: t,
			  maxmin: false,
			  shadeClose: false, //点击遮罩关闭层
			  area : [width+"" , heigth+""],
			  content: url,
			  end:function(){
				  if(calbackurl!=null && calbackurl !=""){
					  loadHtml(calbackurl);
				  }
			  }
		});
	},
	/**
	 * 跳转到页面
	 * @param url 目标地址
	 */
	go2page:function(url){
	    location.href=url;
	},
	/**
	 * 获取数据
	 * @param url 连接
	 * @param param 参数
	 * @param callback 回调方法
	 */
	getApiData:function (url,param,callback,type, opts){
		var index = layer.load();
		var config = $.extend({}, {
			type: type==null? "post": type,
	        url:url,
	        data:param,
	        error: function(request) {
	        	var data = {code:7,msg:'系统异常'};
	        	callback(data);
	        	layer.close(index);
	        },
	        success: function(data) {
	        	if(sysconfig.debug){
	        		console.log(data);
	        	}
	            callback(data);
	            setTimeout(function(){
	            	layer.close(index);
	            }, 100);
	        }
		}, opts);
		$.ajax(config);
	},

	getNoSyncData:function(url,param,callback,type,opts){
		var config = $.extend({}, {
			type: type==null? "post": type,
	        url:url,
	        data:param,
	        async:false,
	        error: function(request) {
	        	var data = {code:7,msg:'系统异常'};
	        	callback(data);
	        },
	        success: function(data) {
	            callback(data);
	        }
		}, opts);
		$.ajax(config);
	},
	/**
	 * 获取浏览器地址栏参数
	 * @param name
	 * @returns
	 */
	GetQueryString:function (name)
	{
	     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	     var search=decodeURI(window.location.search); //编码传输
	     var r = search.substr(1).match(reg);
	     if(r!=null)return  unescape(r[2]); return null;
	},
	/**
	 * 获取 比特格式化后的大小数据
	 * @param bt
	 * @returns {String}
	 */
	filesize:function (bt){
		if(bt/1024/1024/1024>1){
			return (bt/1024/1024/1024).toFixed(2)+"GB";
		}else if(bt/1024/1024>1){
			return (bt/1024/1024).toFixed(2)+"MB";
		}else if(bt/1024>1){
			return (bt/1024).toFixed(2)+"KB";
		}else {
			return bt+"B";
		}
	},
	/**
	 * 获取list操作项的按钮
	 * @param id
	 * @returns {String}
	 */
	getOperHtml:function(id){
		 var  html = '<a class="btn btn-primary btn-xs" onclick="edit('+id+')"><span class="glyphicon glyphicon-pencil"></span>修改</a>&nbsp;';
		 html += '<a class="btn btn-danger btn-xs" onclick="del('+id+')"><span class="glyphicon glyphicon-remove"></span>删除</a>&nbsp;';
		 html += '<a class="btn btn-default btn-xs cmsview" onclick="detail('+id+')"><span class="glyphicon glyphicon-list-alt"></span>详情</a>';
     return html;
	},
	/**
	 * 获取list操作项的按钮
	 * @param id
	 * @returns {String}
	 */
	getOper2Html:function(id){
		var html='';
	     html += '<a class="btn btn-primary btn-xs" onclick="edit('+id+')"><span class="glyphicon glyphicon-pencil"></span>修改</a>&nbsp;';
		html += '<a class="btn btn-danger btn-xs" onclick="del('+id+')"><span class="glyphicon glyphicon-remove"></span>删除</a>';
		return html;
	},
	/**
	 * 返回截取的字符串，并附带title悬停
	 * @param str
	 * @param length
	 */
	substr:function(str,length){
		 var col = str;
		 if(col==null||col.length<=length){
			 return col;
		 }else{
    		 return "<span title='"+col+"'>"+col.substring(0,length-2)+"..."+"</span>";
		 }
	},
	/**
	 * 初始化datatable列表
	 * @param url 请求地址
	 * @param columns 列信息
	 * @returns {___anonymous4155_4345}
	 */
	defaultDatabeConfig:function(url,columns){
		var config = {
			"language": {
		        "url": "${static}/plugin/datatable/media/i18n/zh_cn.json"
		    },
		    bFilter:false,//禁止过滤（隐藏搜索框）
		    ordering:false,//禁止排序
		    ajax: {
		        url: url,
		        dataSrc: 'data'
		    },
		    columns:columns,
		    fnInitComplete:function(oSettings, json) {
		        console.log( 'DataTables 初始化完毕' );
		        sys.initMenuPower();
		    },
		    "sDom":'<"row"<"col-sm-12"t><"clear">><"row"<"col-sm-3"l><"col-sm-4"i><"col-sm-5"p><"clear">>',//改变搜索框的位置
		};
		return config;
	},
	/**
	 * 后台分页
	 */
	DynamicDatabeConfig:function(staticPrefix,url,columns, multiTableCache){
		var noOrderColumn = sys.getDataTableNoOrderIndex(columns);
		//console.log([0].concat(noOrderColumn||[0]));
		var multiTableCache = arguments[2];
		var options = arguments[3];
		var noExportColums = arguments[4]||[];//非导出列
		var ExportColumn = sys.getExportTableColumns(columns,noExportColums);
		var exportExcelStyle =(function(options){
			if(options && options.paging == false){
				return "";
			}
			return "datatable-export-excel";
		})(options);
		var config = {
				"language": {
					"url": staticPrefix+"/plugin/datatable/media/i18n/zh_cn.json"
				},
				ordering:false,
				bLengthChange:true,
				"order":[],
				"aoColumnDefs": [ { "defaultContent": "", "targets": "_all","bSortable": false, "aTargets": [].concat(noOrderColumn||[0]) }],
				 dom: 'Bfrtip',
				 "buttons": [{
					 'action':function(){
						 sys.createSelectModel(this);
					 },
					 'header':true,
					 'title':'',
					 'filename':$.sysDateUtil.getNowFormatDate(),
	                 'extend': 'excel',
	                 'text': '<img class="'+exportExcelStyle+'" src="'+staticPrefix+'/img/device/导出 (7).png" width="23px" height="23px" title="导出excel" />',//定义导出excel按钮的文字
	                 'className': '', //按钮的class样式
	                 'exportOptions': {
	                     'modifier': {
	                         'page': 'current'
	                     },
	                	 columns: ExportColumn
	                 }
	            }],
            	columnDefs: [{"defaultContent": "", "targets": "_all"}],
	            bStateSave: false,
				columns:columns,
				searching:false,
				bProcessing:true, // 是否显示取数据时的那个等待提示
				bServerSide:true,//这个用来指明是通过服务端来取数据
				sAjaxSource:url,//给服务器请求的地址
				fnServerData:retrieveData,// 获取数据的处理函数
				fnInitComplete:function(oSettings, json) {
			        sys.initMenuPower();
			    },
			    fnDrawCallback: function(table) {
			    	var _tableObj = $("#"+table.sTableId).dataTable();
			    	var _oSettings = _tableObj.fnSettings();
			    	var _allPage = (Math.ceil(_oSettings._iRecordsTotal / _oSettings._iDisplayLength)) ;
			    	var _pageIndex = (Math.ceil(_oSettings._iDisplayStart / _oSettings._iDisplayLength) + 1) || 1;//默认第一页
			    	var _footer = $("#"+table.sTableId).parent().parent().next();//底部元素
			    	_footer.find("#redirectPage_Input").val(_pageIndex);//同步
			    	//console.log("当前页码:"+_pageIndex + "总页码:"+_allPage);
			    	if(_footer.find("#redirectPage").length == 0 && !$("#"+table.sTableId).hasClass("noToPage")){
			    		_footer.find(".col-sm-6").append("<span id='redirectPage'>到第<input class='margin text-center' id='redirectPage_Input' type='text'> 页 </span>");
			    		_footer.find("#redirectPage_Input").val(_pageIndex);//同步
			    		_footer.find('#redirectPage_Input').change(function(e) {
			    			var _toPage = Number($(this).val());
			    			if(isNaN(_toPage)){
			    				sys.topmsg("输入页码值不合法");
			    				return ;
			    			}
			    			if(_toPage > _allPage){
			    				sys.topmsg("已超出最大页数");
			    				return ;
			    			}
							if(_toPage && _toPage > 0) {
								var redirectpage =_toPage - 1;
							} else {
								var redirectpage = 0;
							}
							_tableObj.fnPageChange(redirectpage);
						});
			    	}

			    	// 输入选择完成自动搜索
			    	$('.oper-search input').unbind('keypress').bind('keypress', function(event) {
						if (!event) event = window.event;
						if ((event.keyCode || event.which) == 13) {
							$(".oper-search .glyphicon-search").click();
						}
					});
				},
			    "sDom":'<"row"<"col-sm-12"t><"clear">><"row"<"col-sm-3"l><"col-sm-3"i><"col-sm-6 text-right"Bp><"clear">>',//改变搜索框的位置
		};

		if(multiTableCache && window["dataTableArr"]){
			var func = searchCacheManager.get("_tableConfigFromCache");
			func instanceof Function && func(config);
		}else if(window.searchCacheManager){
			searchCacheManager.configTable(config);
		}
		options && $.extend(config, options);
		return config;
	},

	getSimpleRetriveData: function(urlFunc){
		return function( sSource,aoData, fnCallback,oSettings) {
			var _nTable = this;
			sSource = urlFunc instanceof Function? urlFunc(): getSearchUrl();
			var iAoData = {};
			var set = {iDisplayStart: true, iDisplayLength: true, sEcho: true,iSortCol_0:true,sSortDir_0:true}
			for(var i = 0; i < aoData.length; i++){
				var item = aoData[i];
				if(set[item.name]){
					iAoData[item.name] = item.value
				}
			}
			var sEcho = iAoData.sEcho;//这个玩意纪录的是列表操作的次数，前后段保持一致即可
			var pageindex = (Math.ceil(iAoData.iDisplayStart / iAoData.iDisplayLength) + 1) ;
			var param = "pagesize=" + iAoData.iDisplayLength
			+"&ordercolumn="+sys.getDataTableColumnName(aoData,iAoData.iSortCol_0)
			+"&orderdir="+(iAoData.sSortDir_0 || "desc");

			_getTableData(sSource,param,pageindex,sEcho);

			function _getTableData(sSource,param,pageindex,sEcho){
				var newParam = param+"&pageindex="+pageindex+"&sEcho="+sEcho;
				$.post(sSource,newParam, function(result){
					//console.log(result);
                    var allPageNumber = result.iTotalRecords;
                    var nowPageNumber = result.aaData.length;
					if(pageindex !=1 && nowPageNumber === 0){
						//getData(sSource,param,1,1);
						_nTable.api().ajax.url(sSource+newParam).load();
					}else{
						fnCallback(result);
				    	sys.initMenuPower();
					}
				});
			}
		}
	},

	useSimpleRetrieveData:function(urlFunc){
		retrieveData = sys.getSimpleRetriveData(urlFunc);
	},

	createSelectModel:function(that){
		var _instanceId = _tableId = that.context[0].sTableId;
		var _table =  $("#"+_instanceId);
		var _value = [];
		if(_instanceId && _table.length>0){
			var _thLength = _table.find("thead tr th,thead tr td").length || 0;
			_table.find("thead tr th,thead tr td").each(function(i,ele){
				var _lastThHtml = _table.find("thead tr>*:last").html();
				if( _thLength == i+1 && _lastThHtml.indexOf("操作")>-1){
					return true;
				}
				_value.push({index:i,name:$(this).html()});
			})
		}
		var _content = "";
		_value.forEach(function(v){
			// 去掉导入表格头中的问号提示, 过滤span标签
			var name = v.name;
			if (v.name.indexOf('<span') != -1) {
				name = v.name.substring(0, v.name.indexOf('<span')-5);
			}

			_content+='<div class="mode_column-li">'
				 +'<div class="pretty o-success">'
				 +' <input type="checkbox" checked value='+v.index+' /> '
				 +'   <label><i class="mdi mdi-check"></i></label>'
				 +'</div>'
				+name+'</div>';
		})
		_content = "<div class='mode_content_parent'>"+_content+"</div>"
		var _bg = "<div class='mode_bg' style='' onclick='sys.closeColumnsMode(this)'></div>";
		var _close = '<div class="layui-layer-title" style="cursor: move;">选择导出项</div><span onclick="sys.closeColumnsMode(this)" class="layui-layer-setwin"><a class="layui-layer-ico layui-layer-close layui-layer-close1" href="javascript:;"></a></span>';
		var _subBtn = "<div class='mode-bottom'><div class='mode-sub btn btn-success' onclick='sys.subExportExcel(this,"+_tableId+")'>导出</div></div>";
		var _model = "<div class='mode_content'>"+_close+_content+_subBtn+"</div>";
	    $("body").append(_model);
		$("body").append(_bg);

	},

	subExportExcel:function(that,_table){
		var eI = [];
		var notExportColumn = [];
		$(that).parents(".mode_content").find("input[type='checkbox']").each(function(index,ele){
			if($(this).is(":checked")){
				eI.push($(this).val());
			}else{
				notExportColumn.push(index);
			}
		})
		if(eI.length == 0){
			sys.topmsg("至少导出一项!");
			return ;
		};
		_tableId = _table.id || _table[0].id;
		var table = $('#'+_tableId).DataTable();
		var data = table.buttons.exportData( {
			columns:eI,
			stripHtml:true
		});
		var config = table.buttons.exportInfo( {
			columns:eI
		});
		var config = $.extend({},{},{
			 'header':true,
			 'title':'',
			 'filename':$.sdu.getNowFormatDate(),
             'extend': 'excel',
             'text': '导出为Excel',//定义导出excel按钮的文字
             'className': 'btn btn-sm glyphicon glyphicon-export', //按钮的class样式
             'exportOptions': {
                 'modifier': {
                     'page': 'current'
                 },
            	 columns: eI,
            	 stripHtml:true
             }
		});
		console.log(data);
		console.log(config);
		if(!data){
			sys.topmsg("该列表不支持导出到excel");
			return ;
		}

		sys.exportTableToExcel(data);

	},

	exportTableToExcel:function(data){

		 var url = "ete/saveExcelData";
		 var param= {
				 header:JSON.stringify(data.header),
				 body:JSON.stringify(data.body),
				 filename:$.sdu.getNowFormatDate(),
		 };
		 $.post(url,param,function(data){
			 location.href = "ete/exportExcel";
		 });

	},


	closeColumnsMode:function(that){
		$(".mode_content").remove();
		$(".mode_bg").remove();
	},

	getExportTableColumns:function(columns,notExports){
		var r = [];
		for(var key in columns){
			r.push(parseInt(key));
		}
		if(columns && notExports && notExports.length>0){
			for(var key in notExports){
				var v = notExports[key];
				var i = r.indexOf(v);
				if(i>-1){
					r.splice(i,1);
				}
			}
		}
		return r;
	},

	getDataTableNoOrderIndex:function(columns){
		let arr = [];
		if(columns && columns.length>0){
			for(var key in columns){
				var v = columns[key];
				if(!v["data"]){
					arr.push(parseInt(key));
				}
			}
		}
		return arr;
	},
	getDataTableColumnName:function(aoData,index){
		var  column = "";
		if(aoData && aoData.length>0){
			for(var key in aoData){
				var v = aoData[key];
				if(v.name == "mDataProp_"+index){
					column = v.value ;
					break ;
				}
			}
		}
		return column;
	},
	/**
	 * 验证信息是否为空
	 * @param data [{value:$("#username").value(),title:"用户名称"}]
	 * @returns {Boolean}
	 */
	validateNull:function(data){
		if(data==null||data.length==0){
			return false;
		}
		for(var i=0;i<data.length;i++){
			var d = data[i];
			if(d.value==null||d.value==""){
				sys.topmsg(d.title+(d.msg==null?"不能为空！":d.msg));
				return false;
			}
		}
		return true;
	},
	validatePhone:function(data){
		if(!(/^1[34578]\d{9}$/.test(data))){
			sys.topmsg("手机格式不符合规范");
			return false;
		}
		return true;
	},
	validateAccount:function(data){
		if(!(/^1[34578]\d{9}$/.test(data))){
			sys.topmsg("账号必须是手机号");
			return false;
		}
		return true;
	},
	validateEmail:function(data){
		if(!(/^[A-Za-z0-9\u4e00-\u9fa5_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(data))){
			sys.topmsg("邮箱不符合规范");
			return false;
		}
		return true;
	},
	validateIDCard:function(data){
		if(!(/^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/.test(data))){
			sys.topmsg("身份证号不符合规范");
			return false;
		}
		return true;
	},
	validateNumber:function(data){
		if(!(/^[0-9]*$/.test(data))){
			sys.topmsg("年龄必须是整数");
			return false;
		}
		return true;
	},
	getBirthdayFromIdCard : function(idCard) {
        var birthday = "";
        if(idCard != null && idCard != ""){
            if(idCard.length == 15){
                birthday = "19"+idCard.substr(6,6);
            } else if(idCard.length == 18){
                birthday = idCard.substr(6,8);
            }

            birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
        }

        return birthday;
      },
      getSex:function(psidno){
    	    var sexno,sex
    	    if(psidno.length==18){
    	        sexno=psidno.substring(16,17)
    	    }else if(psidno.length==15){
    	        sexno=psidno.substring(14,15)
    	    }else{
    	        alert("错误的身份证号码，请核对！")
    	        return false
    	    }
    	    var tempid=sexno%2;
    	    if(tempid==0){
    	        sex='1'
    	    }else{
    	        sex='0'//男
    	    }
    	    return sex
    	},
       disableForm:function(formId,isDisabled) {

    	    var attr="disable";
    	    if(!isDisabled){
    	       attr="enable";
    	    }
    	    $("form[id='"+formId+"'] :text").attr("disabled",isDisabled);
    	    $("form[id='"+formId+"'] textarea").attr("disabled",isDisabled);
    	    $("form[id='"+formId+"'] select").attr("disabled",isDisabled);
    	    $("form[id='"+formId+"'] :radio").attr("disabled",isDisabled);
    	    $("form[id='"+formId+"'] :checkbox").attr("disabled",isDisabled);

    	    //禁用jquery easyui中的下拉选（使用input生成的combox）

    	    $("#" + formId + " input[class='combobox-f combo-f']").each(function () {
    	        if (this.id) {alert("input"+this.id);
    	            $("#" + this.id).combobox(attr);
    	        }
    	    });

    	    //禁用jquery easyui中的下拉选（使用select生成的combox）
    	    $("#" + formId + " select[class='combobox-f combo-f']").each(function () {
    	        if (this.id) {
    	        alert(this.id);
    	            $("#" + this.id).combobox(attr);
    	        }
    	    });

    	    //禁用jquery easyui中的日期组件dataBox
    	    $("#" + formId + " input[class='datebox-f combo-f']").each(function () {
    	        if (this.id) {
    	        alert(this.id)
    	            $("#" + this.id).datebox(attr);
    	        }
    	    });
    	},

    	dtGroupConcat: function(t){
    		 var nTrs = t.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
    		 var arr = [];
           for(var i = 0; i < nTrs.length; i++){
               var d = t.fnGetData(nTrs[i]);
               arr.push(d.id);
           }
           return arr.join(",");
    	},
    	stopPropagation:function () {
	        var e = window.event;
	        if(e){
	        	if(e.stopPropagation) { //W3C阻止冒泡方法
		            e.stopPropagation();
		        } else  {
		            e.cancelBubble = true; //IE阻止冒泡方法
		        }
	        }
	    },


}

function formatJavaString(){
    $(".datetime-format").each(function(){
        var res = $(this).text();
        if(typeof res == "string" && res.indexOf(".") > -1){
            $(this).text(res.split(".")[0])
        }
    })
    $(".float-format").each(function(){
        var res = $(this).text();
        if(typeof res == "string" && res.indexOf(".") > -1){
            $(this).text(parseFloat(res))
        }
    })
}

/**
 * 自定义replaceAll
 * @return
 */
String.prototype.replaceAll  = function(s1,s2){     
    return this.replace(new RegExp(s1,"gm"),s2);     
}


var wxDebugTool = {
		login: function(id){
			$.post("dlTestM1996", {id: id}, function(data){
				sys.msg(data);
			})
		},
		logout: function(){
			$.post("dlTestC1996", {}, function(data){
				sys.msg(data);
			})
		}
}

function getSearchCacheManager(selector){
	var obj = localStorage.setItem("__SearchCacheManager","__SearchCacheManager");
	if(obj){
		return JSON.parse(obj);
	}else {
		return new SearchCacheManager(selector);
	}
}

function SearchCacheManager(cacheInputSelector){
	this.__cache = {};
	this.__currentSpaceName = void(0);
	var __this = this;

	this.put = function(k, v){
		this.getCurrentCache(this.__currentSpaceName)[k] = v;
	}

	this.get = function(k){
		return this.getCurrentCache(this.__currentSpaceName)[k];
	}

	this.save = function(){
		if(!this.__currentSpaceName){
			return -1;
		}
		this.ifExsitsTable(function(table){
			var fnSetting = table.fnSettings();
			if(!fnSetting){
				return;
			}
			__this.put("_iDisplayLength",fnSetting._iDisplayLength);
			__this.put("_iDisplayStart", fnSetting._iDisplayStart);
		});
		if(window["dataTableArr"]){
			var arr = [];
			for(var i = 0; i < dataTableArr.length; i++){
				var d = dataTableArr[i];
				var fnSetting = d.fnSettings();
				if(!fnSetting){
					continue ;
				}
				arr.push({_iDisplayLength: fnSetting._iDisplayLength, _iDisplayStart: fnSetting._iDisplayStart});
			}
			this.put("_tableConfigFromCache", (function(arr){
				var i = 0;
				return function(config){
					var c = arr[i];
					var _iDisplayLength = c._iDisplayLength;
					var _iDisplayStart = c._iDisplayStart;
					if(_iDisplayLength){
						config.pageLength = _iDisplayLength;
					}
					if(_iDisplayStart){
						config.displayStart = _iDisplayStart;
					}
					i++;
				}
			})(arr));
		}
		var arr = [];
		this.eachInput(function(e, i){
			if(e.is(".selectpicker") && e.selectpicker instanceof Function){
				arr.push(e.selectpicker("val"));
			}else if(e.is("[type='checkbox']") || e.is("[type='radio']")){
				arr.push(e.is(":checked"));
			} else {
				arr.push(e.val());
			}
		});
		this.put("inputs", arr);
	}

	this.load = function(){
		var arr = this.get("inputs");
		if(arr && arr.length){
			this.eachInput(function(e, i){
				if(e.is("[search-cache-forbidden]")){
					return;
				}
				if(e.is(".selectpicker") && e.selectpicker instanceof Function){
					e.selectpicker("val", arr[i]);
					e.val(arr[i]);
				}else if(e.is("[type='checkbox']") || e.is("[type='radio']")){
					e[0].checked = !!arr[i];
				} else {
					e.val(arr[i]);
				}
			});
		}
		this.ready();
	}
	this.getTable = function(){
		return window["dataTable"];
	}
	this.ifExsitsTable = function(func){
		var table = this.getTable();
		if(table){
			func(table);
		}
	}
	this.configTable = function(config){
		var _iDisplayLength = this.get("_iDisplayLength");
		var _iDisplayStart = this.get("_iDisplayStart");
		if(_iDisplayLength){
			config.pageLength = _iDisplayLength;
		}
		if(_iDisplayStart){
			config.displayStart = _iDisplayStart;
		}
	}

	this.ready = function(){}
	this.eachInput = function(func){
		var inputs = this.getInputs();
		for(var i = 0; i < inputs.length; i++){
			func(inputs.eq(i), i, inputs);
		}
	}
	this.getInputs = function(){
		return $(cacheInputSelector);
	}

	this.setCurrentKey = function(spaceName){
		this.__currentSpaceName = spaceName;
	}
	this.getCurrentCache = function(k){
		var cache = this.__cache[this.__currentSpaceName];
		if(!cache){
			cache = {};
			this.__cache[this.__currentSpaceName] = cache;
		}
		return cache;
	}
}



function DelayZtree(ztreeEl, url, onClick, initCallback){
	var dataprocess = function(data){
		if(data.code == 0){
			var arr = data.data;
			var l = arr.length;
			for(var i = 0; i < l; i++){
				var d = arr[i];
				if(d.children_count === undefined){
					d.isParent = true;
				}else {
					d.isParent = !!d.children_count;
				}
			}
			return arr;
		}
		return [];
	}
	var setting = {
			view : {
				expandSpeed : 100,
				nameIsHTML : true
			},
			data : {
				simpleData : {
					enable : true,
					idKey : "id",
					pIdKey : "pid",
					rootPId : 0
				}
			},
			callback: {
				beforeExpand: function(treeId, treeNode){
					console.log(treeNode);
					if(!(treeNode.children && treeNode.children.length)){
						$.getJSON(url, {pid: treeNode.id}, function(data){
							ztree.addNodes(treeNode, dataprocess(data));
						});
					}
				},
				onClick: onClick,
			},
	};
	var ztree;
	var ztreeEl;
	var url;


	$.getJSON(url, {pid: ''}, function(data){
		ztree = $.fn.zTree.init(ztreeEl, setting, dataprocess(data));
		if (initCallback && initCallback instanceof Function) {
			console.log(data);
			initCallback(ztree, data);
		}
	});
}


function initSelectByMap(select, map, selected){
	var html = "";
	for(var value in map){
		var text = map[value];
		html += "<option value='"+value+"' "+(value == selected? " selected ": "")+">"+text+"</option>";
	}
	$(select).append(html);
}

var LocalCache = (function(){
	var _store = "cookie";
	return {
		use: function(store){
			_store = store;
		},
		get: function(k, type){
			if(_store === "cookie"){
				var v = $.cookie(k);
				if(type === "json"){
					return JSON.parse(v);
				}else {
					return v;
				}
			}
		},
		set: function(k, value){
			if(_store === "cookie"){
				$.cookie(k, value instanceof Object? JSON.stringify(value): value, {expires: 19961008});
			}
		},
		remove: function(k){
			if(_store === "cookie"){
				$.cookie(k, null, {expires: -1});
			}
		}
	};
})();

function tableColumnDisplay(datatable, visibleCols, hideOther){
	 var arr = datatable.columns().visible();

	  var map = {};
	  for(var i = 0; i < visibleCols.length; i++){
		  map[visibleCols[i]] = true;
	  }
	  var to_be_visible = [];
	  for(var i = 0; i < arr.length; i++){
		  if(!arr[i] && !map[i]){
			  to_be_visible.push(i);
		  }
	  }
	  datatable.columns(to_be_visible).visible(true);
	  datatable.columns(visibleCols).visible(false);
}
